{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 智能体(Agent)\n",
    "ERNIE Bot Agent 基于文心大模型的 Function Calling 能力实现了多工具编排和自动调度功能，并且允许工具、插件、知识库等不同组件的混合编排。\n",
    "除了自动调度，我们未来还将支持更多的编排模式，例如手动编排、半自动编排，为开发者提供更大的灵活性。\n",
    "在开始本教程前，我们需要先获取[飞桨AI Studio星河社区的access_token](https://aistudio.baidu.com/index/accessToken)并且其配置成环境变量，对调用大模型和工具中心进行鉴权。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Function Agent介绍\n",
    "在此教程中，主要介绍一个自动智能调度的Function Agent的运行过程，Function Agent的编排能力由集成的LLM大语言模型（此处为文心）的函数调用能力驱动。\n",
    "通常由Agent将用户的自然语言输入传递请求LLM生成一个可以解析的Action，\n",
    "然后Agent根据Action，调用相应的工具或插件，然后完成此操作并再次请求LLM决定是否要产生下一个Action或者终止。\n",
    "\n",
    "一个智能体的运行大致分为以下三步：\n",
    "1. 创建需要调用的工具\n",
    "2. 创建智能体\n",
    "3. 调用智能体\n",
    "\n",
    "[Optional]建议将环境变量`EB_AGENT_LOGGING_LEVEL`设置为info打开相关日志，以方便观察智能体具体的运行过程。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "接下来将按照这三步，结合一个具体的实例进行介绍：\n",
    "\n",
    "实例的背景为创建一个英语学习智能体，帮助用户学习英语单词，包括单词的释义、近义词、反义词和例句并将相关信息添加到单词本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"EB_AGENT_LOGGING_LEVEL\"] = \"INFO\"\n",
    "os.environ[\"EB_AGENT_ACCESS_TOKEN\"] = \"<access_token>\"\n",
    "\n",
    "from pydantic import Field\n",
    "from typing import Dict, Type, Any\n",
    "\n",
    "from erniebot_agent.chat_models import ERNIEBot\n",
    "from erniebot_agent.memory import HumanMessage, SlidingWindowMemory\n",
    "from erniebot_agent.tools.base import Tool\n",
    "from erniebot_agent.tools.schema import ToolParameterView\n",
    "from erniebot_agent.agents import FunctionAgent\n",
    "from erniebot_agent.tools import RemoteToolkit\n",
    "from erniebot_agent.file import GlobalFileManagerHandler"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建工具\n",
    "此章节中，主要展示如何创建用于英语学习智能体相关的本地工具以及远程工具，以便于用户直接体验，不会对tool的相关内容有太多详细的介绍，关于tool的详细内容，详见[Tool入门](https://ernie-bot-agent.readthedocs.io/zh-cn/latest/cookbooks/agent/tools_intro/)。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义ChatWithEB工具\n",
    "在智能体(Agent)中，我们创建一个名为ChatWithEB的工具，该工具用于为用户的单词提供详细的释义，其中可以通过`prompt`或者`system`的方式来控制，达成用户的相关目标（本例中为按要求获取单词相关信息）。\n",
    "\n",
    "同时`ChatWithEB`工具也是一个推荐的本地工具，加载在智能体当中用于每一个Run中途的交互，从而更好地完成智能体的功能。\n",
    "\n",
    "例如在本例中，我们通过`ChatWithEB`工具来获取用户输入的单词的详细信息，进而能直接添加进入单词本当中。\n",
    "\n",
    "如果不使用这个工具，那么用户无法通过一句简单的\"帮我添加单词\"同时执行这三个操作：\n",
    "\n",
    "需要先通过OCR获得单词内容，然后开启下一轮对话通过prompt获得单词相关内容，然后再通过\"帮我添加单词\"添加相关单词。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ChatWithEBInputView(ToolParameterView):\n",
    "    word: str = Field(description=\"需要获取详细信息的单词\")\n",
    "\n",
    "\n",
    "class ChatWithEBOutputView(ToolParameterView):\n",
    "    response: str = Field(description=\"单词的详细释义\")\n",
    "\n",
    "\n",
    "class ChatWithEB(Tool):\n",
    "    description: str = \"ChatWithEB是一款根据用户的提供的单词，获取一个具体的单词描述、翻译以及例句的工具\"\n",
    "    input_type: Type[ToolParameterView] = ChatWithEBInputView\n",
    "    output_type: Type[ToolParameterView] = ChatWithEBOutputView\n",
    "\n",
    "    def __init__(self, llm: ERNIEBot):\n",
    "        self.llm = llm\n",
    "\n",
    "    async def __call__(self, word: str) -> Dict[str, str]:\n",
    "        prompt = f\"请告诉我{word}的详细信息，以下面的格式输出（其中单词翻译需要是中文，其他为英语）\" \"<单词翻译>:\\n<近义词>:\\n<反义词>:\\n<例句>:\\n\"\n",
    "        response = await self.llm.chat([HumanMessage(prompt)])\n",
    "        return {\"response\": response.content}\n",
    "\n",
    "\n",
    "SYSTEM_MESSAGE = \"你是一个英语老师，当用户给你一个单词的时候，请你专业而通俗的返回英语的<单词翻译><近义词><反义词><例句>\"\n",
    "llm = ERNIEBot(model=\"ernie-4.0\", system=SYSTEM_MESSAGE)\n",
    "word_helper_tool = ChatWithEB(llm)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义AddWordTool工具\n",
    "在此智能体(Agent)中，我们创建一个名为AddWordTool的工具，用于将用户的单词添加至单词本。此工具为`Tool`章节中的示例工具，此处不做过多介绍。详见[Tool入门](https://ernie-bot-agent.readthedocs.io/zh-cn/latest/cookbooks/agent/tools_intro/)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class AddWordInput(ToolParameterView):\n",
    "    word: str = Field(description=\"待添加的单词\")\n",
    "    des: str = Field(description=\"待添加的单词的详细释义,含有<单词翻译><近义词><反义词><例句>\")\n",
    "\n",
    "\n",
    "class AddWordOutput(ToolParameterView):\n",
    "    result: str = Field(description=\"表示是否成功将单词成功添加到词库当中\")\n",
    "\n",
    "\n",
    "class AddWordTool(Tool):\n",
    "    description: str = \"添加单词以及它的详细解释到词库当中\"\n",
    "    input_type: Type[ToolParameterView] = AddWordInput\n",
    "    output_type: Type[ToolParameterView] = AddWordOutput\n",
    "\n",
    "    def __init__(self) -> None:\n",
    "        self.word_books = {}\n",
    "        super().__init__()\n",
    "\n",
    "    async def __call__(self, word: str, des: str) -> Dict[str, Any]:\n",
    "        if word in self.word_books:\n",
    "            return {\"result\": f\"<{word}>单词已经存在，无需添加\"}\n",
    "        self.word_books[word] = des\n",
    "        words = \"\\n\".join(list(self.word_books.keys()))\n",
    "        return {\"result\": f\"<{word}>单词已添加成功, 当前单词本中有如下单词：{words}，释义如下{des}\"}\n",
    "\n",
    "\n",
    "add_word_tool = AddWordTool()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 从AIStudio导入RemoteTool\n",
    "此处不做过多介绍。详见[RemoteTool相关文档](https://ernie-bot-agent.readthedocs.io/zh-cn/latest/cookbooks/agent/remote-tool/remote_tool/)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "ocr_tool = RemoteToolkit.from_aistudio(\"highacc-ocr\").get_tools()[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建智能体\n",
    "在此步骤中将展示如何创建智能体。\n",
    "\n",
    "1. 指定调用的文心大模型，通过`enable_multi_step_tool_call`接口打开multi_tool_call功能，开启之后即可通过一个指令进行多次不同工具的调用，通过`max_steps`控制此Run中执行的最大的Step以免一直循环。\n",
    "\n",
    "2. 为智能体添加默认的`ChatWithEB`和`AddWordTool`工具。\n",
    "\n",
    "3. [Optional]为智能体指定特殊的`Memory`，默认为`WholeMemory`，详见[memory机制讲解](https://ernie-bot-agent.readthedocs.io/zh-cn/latest/cookbooks/agent/memory/)。\n",
    "\n",
    "4. [Optional]为智能体指定`SystemMessage`，设置全局的指令。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = SlidingWindowMemory(max_round=5)\n",
    "llm_final = ERNIEBot(model=\"ernie-3.5\", api_type=\"aistudio\", enable_multi_step_tool_call=True)\n",
    "agent_all = FunctionAgent(llm=llm_final, tools=[word_helper_tool, add_word_tool, ocr_tool], memory=memory)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调用智能体\n",
    "在完成了智能体创建之后，通过异步run函数执行指令，并获取返回结果（如果打开了multi_tool_call，那么仅需一句指令即可同时执行图片OCR，单词解释以及添加至单词本三个动作）。\n",
    "\n",
    "如果需要运行过程中涉及到文件，可以先通过`file_manager`创建`File`对象，再通过run的`files`参数传入。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2023-12-28 18:10:19--  https://paddlenlp.bj.bcebos.com/datasets/examples/road_sign.jpeg\n",
      "Resolving paddlenlp.bj.bcebos.com (paddlenlp.bj.bcebos.com)... 36.110.192.178\n",
      "Connecting to paddlenlp.bj.bcebos.com (paddlenlp.bj.bcebos.com)|36.110.192.178|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 44056 (43K) [image/jpeg]\n",
      "Saving to: 'road_sign.jpeg'\n",
      "\n",
      "road_sign.jpeg      100%[===================>]  43.02K  --.-KB/s    in 0.06s   \n",
      "\n",
      "2023-12-28 18:10:20 (695 KB/s) - 'road_sign.jpeg' saved [44056/44056]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!wget https://paddlenlp.bj.bcebos.com/datasets/examples/road_sign.jpeg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[92mINFO - [Run][Start] FunctionAgent is about to start running with input:\n",
      "\u001b[94m帮我把图片中的第一个英语单词进行解释之后添加到单词本中\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [LLM][Start] ERNIEBot is about to start running with input:\n",
      " role: \u001b[94muser\u001b[92m \n",
      " content: \u001b[94m帮我把图片中的第一个英语单词进行解释之后添加到单词本中\n",
      "<file>file-local-4ea15200-a569-11ee-a73d-56c70f692df9</file>\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [LLM][End] ERNIEBot finished running with output:\n",
      " role: \u001b[93massistant\u001b[92m \n",
      " function_call: \u001b[93m\n",
      "{\n",
      "  \"name\": \"highacc-ocr/v1.8/OCR\",\n",
      "  \"thoughts\": \"用户需要我识别图片中的文字，并把第一个英语单词添加到单词本中。我需要先使用OCR工具提取图片中的文字，然后使用ChatWithEB工具获取单词的详细信息，最后使用AddWordTool工具将单词添加到词库中。任务拆解：[sub-task1: 使用OCR工具提取图片中的文字，sub-task2: 使用ChatWithEB工具获取单词的详细信息，sub-task3: 使用AddWordTool工具将单词添加到词库中]。接下来我需要调用[highacc-ocr/v1.8/OCR]来提取图片中的文字。\",\n",
      "  \"arguments\": \"{\\\"image\\\":\\\"file-local-4ea15200-a569-11ee-a73d-56c70f692df9\\\",\\\"language_type\\\":\\\"ENG\\\"}\"\n",
      "}\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [Tool][Start] \u001b[95mRemoteTool\u001b[92m is about to start running with input:\n",
      "\u001b[95m{\n",
      "  \"image\": \"file-local-4ea15200-a569-11ee-a73d-56c70f692df9\",\n",
      "  \"language_type\": \"ENG\"\n",
      "}\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [Tool][End] \u001b[95mRemoteTool\u001b[92m finished running with output:\n",
      "\u001b[95m{\n",
      "  \"words_result\": [\n",
      "    \"BEWARE\",\n",
      "    \"OF FALLING\",\n",
      "    \"COCONUTS\"\n",
      "  ],\n",
      "  \"words_result_num\": 3\n",
      "}\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [LLM][Start] ERNIEBot is about to start running with input:\n",
      " role: \u001b[95mfunction\u001b[92m \n",
      " name: \u001b[95mhighacc-ocr/v1.8/OCR\u001b[92m \n",
      " content: \u001b[95m{\"words_result\": [\"BEWARE\", \"OF FALLING\", \"COCONUTS\"], \"words_result_num\": 3}\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [LLM][End] ERNIEBot finished running with output:\n",
      " role: \u001b[93massistant\u001b[92m \n",
      " function_call: \u001b[93m\n",
      "{\n",
      "  \"name\": \"ChatWithEB\",\n",
      "  \"thoughts\": \"我已经从图片中提取出了文字，现在我需要使用ChatWithEB工具获取第一个英语单词的详细信息。\",\n",
      "  \"arguments\": \"{\\\"word\\\":\\\"BEWARE\\\"}\"\n",
      "}\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [Tool][Start] \u001b[95mChatWithEB\u001b[92m is about to start running with input:\n",
      "\u001b[95m{\n",
      "  \"word\": \"BEWARE\"\n",
      "}\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [Tool][End] \u001b[95mChatWithEB\u001b[92m finished running with output:\n",
      "\u001b[95m{\n",
      "  \"response\": \"<单词翻译>: 当心、小心\\n\\n<近义词>: Careful, Cautious, Wary, Alert\\n\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\n\\n<例句>:\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\n3. Beware of the icy road, it's very slippery. (小心结冰的路面，非常滑。)\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"\n",
      "}\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [LLM][Start] ERNIEBot is about to start running with input:\n",
      " role: \u001b[95mfunction\u001b[92m \n",
      " name: \u001b[95mChatWithEB\u001b[92m \n",
      " content: \u001b[95m{\"response\": \"<单词翻译>: 当心、小心\\n\\n<近义词>: Careful, Cautious, Wary, Alert\\n\\n<反义词>: Reckless, Careless, N...\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [LLM][End] ERNIEBot finished running with output:\n",
      " role: \u001b[93massistant\u001b[92m \n",
      " function_call: \u001b[93m\n",
      "{\n",
      "  \"name\": \"AddWordTool\",\n",
      "  \"thoughts\": \"我已经获取到了第一个英语单词的详细信息，现在我需要使用AddWordTool工具将这个单词添加到词库中。\",\n",
      "  \"arguments\": \"{\\\"word\\\":\\\"BEWARE\\\",\\\"des\\\":\\\"<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it's very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\\\"}\"\n",
      "}\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [Tool][Start] \u001b[95mAddWordTool\u001b[92m is about to start running with input:\n",
      "\u001b[95m{\n",
      "  \"word\": \"BEWARE\",\n",
      "  \"des\": \"<单词翻译>: 当心、小心\\n\\n<近义词>: Careful, Cautious, Wary, Alert\\n\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\n\\n<例句>:\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\n3. Beware of the icy road, it's very slippery. (小心结冰的路面，非常滑。)\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"\n",
      "}\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [Tool][End] \u001b[95mAddWordTool\u001b[92m finished running with output:\n",
      "\u001b[95m{\n",
      "  \"result\": \"<BEWARE>单词已添加成功, 当前单词本中有如下单词：BEWARE，释义如下<单词翻译>: 当心、小心\\n\\n<近义词>: Careful, Cautious, Wary, Alert\\n\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\n\\n<例句>:\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\n3. Beware of the icy road, it's very slippery. (小心结冰的路面，非常滑。)\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"\n",
      "}\u001b[92m\u001b[0m\n",
      "\u001b[92mINFO - [LLM][Start] ERNIEBot is about to start running with input:\n",
      " role: \u001b[95mfunction\u001b[92m \n",
      " name: \u001b[95mAddWordTool\u001b[92m \n",
      " content: \u001b[95m{\"result\": \"<BEWARE>单词已添加成功, 当前单词本中有如下单词：BEWARE，释义如下<单词翻译>: 当心、小心\\n\\n<近义词>: Careful, Cautious, Wary,...\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [LLM][End] ERNIEBot finished running with output:\n",
      " role: \u001b[93massistant\u001b[92m \n",
      " content: \u001b[93m我已经将BEWARE这个单词添加到单词本中，它的意思是当心、小心，还有其他的释义和例句。如果您还有其他问题或需要添加更多单词，请随时告诉我。\u001b[92m \u001b[0m\n",
      "\u001b[92mINFO - [Run][End] FunctionAgent finished running.\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "file_manager = GlobalFileManagerHandler().get()\n",
    "file = await file_manager.create_file_from_path(r\"./road_sign.jpeg\")\n",
    "response = await agent_all.run(\"帮我把图片中的第一个英语单词进行解释之后添加到单词本中\", files=[file])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我已经将BEWARE这个单词添加到单词本中，它的意思是当心、小心，还有其他的释义和例句。如果您还有其他问题或需要添加更多单词，请随时告诉我。\n"
     ]
    }
   ],
   "source": [
    "print(response.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'BEWARE': \"<单词翻译>: 当心、小心\\n\\n<近义词>: Careful, Cautious, Wary, Alert\\n\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\n\\n<例句>:\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\n3. Beware of the icy road, it's very slippery. (小心结冰的路面，非常滑。)\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add_word_tool.word_books"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Agent其他相关方法\n",
    "除了上述主要功能以外，接下来这个章节主要用于介绍一些其他可能会使用到的智能体功能。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### AgentResponse\n",
    "\n",
    "AgentResponse作为智能体返回的结果，主要包含以下内容：\n",
    "1. `text`: Agent在本Run中返回的最终文本\n",
    "2. `steps`: Agent在本Run中执行的Step。\n",
    "    含有tool_name（调用工具的名称），tool_args（工具的入参），input_files（输入的文件）， output_files（输出的文件）\n",
    "    \n",
    "    **Agent在步骤中涉及到的文件将存放在Step中，包括输入文件以及输出文件** \n",
    "3. `chat_history`: Agent在本Run中的对话历史\n",
    "4. `status`: 包括`FINISHED`和`STOPPED`，其中`FINISHED`表示正常结束，`STOPPED`表示智能体因达到最大step数目强行终止"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<HumanMessage role: 'user', content: '帮我把图片中的第一个英语单词进行解释之后添加到单词本中\\n<file>file-local-4ea15200-a569-11ee-a73d-56c70f692df9</file>', token_count: 1110>,\n",
       " <AIMessage role: 'assistant', function_call: {'name': 'highacc-ocr/v1.8/OCR', 'thoughts': '用户需要我识别图片中的文字，并把第一个英语单词添加到单词本中。我需要先使用OCR工具提取图片中的文字，然后使用ChatWithEB工具获取单词的详细信息，最后使用AddWordTool工具将单词添加到词库中。任务拆解：[sub-task1: 使用OCR工具提取图片中的文字，sub-task2: 使用ChatWithEB工具获取单词的详细信息，sub-task3: 使用AddWordTool工具将单词添加到词库中]。接下来我需要调用[highacc-ocr/v1.8/OCR]来提取图片中的文字。', 'arguments': '{\"image\":\"file-local-4ea15200-a569-11ee-a73d-56c70f692df9\",\"language_type\":\"ENG\"}'}, token_count: 190>,\n",
       " <FunctionMessage role: 'function', name: 'highacc-ocr/v1.8/OCR', content: '{\"words_result\": [\"BEWARE\", \"OF FALLING\", \"COCONUTS\"], \"words_result_num\": 3}'>,\n",
       " <AIMessage role: 'assistant', function_call: {'name': 'ChatWithEB', 'thoughts': '我已经从图片中提取出了文字，现在我需要使用ChatWithEB工具获取第一个英语单词的详细信息。', 'arguments': '{\"word\":\"BEWARE\"}'}, token_count: 32>,\n",
       " <FunctionMessage role: 'function', name: 'ChatWithEB', content: '{\"response\": \"<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it\\'s very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}'>,\n",
       " <AIMessage role: 'assistant', function_call: {'name': 'AddWordTool', 'thoughts': '我已经获取到了第一个英语单词的详细信息，现在我需要使用AddWordTool工具将这个单词添加到词库中。', 'arguments': '{\"word\":\"BEWARE\",\"des\":\"<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it\\'s very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}'}, token_count: 235>,\n",
       " <FunctionMessage role: 'function', name: 'AddWordTool', content: '{\"result\": \"<BEWARE>单词已添加成功, 当前单词本中有如下单词：BEWARE，释义如下<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it\\'s very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}'>,\n",
       " <AIMessage role: 'assistant', content: '我已经将BEWARE这个单词添加到单词本中，它的意思是当心、小心，还有其他的释义和例句。如果您还有其他问题或需要添加更多单词，请随时告诉我。', token_count: 39>]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.chat_history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'FINISHED'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.status"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ToolStep(info={'tool_name': 'highacc-ocr/v1.8/OCR', 'tool_args': '{\"image\":\"file-local-4ea15200-a569-11ee-a73d-56c70f692df9\",\"language_type\":\"ENG\"}'}, result='{\"words_result\": [\"BEWARE\", \"OF FALLING\", \"COCONUTS\"], \"words_result_num\": 3}', input_files=[<LocalFile id: 'file-local-4ea15200-a569-11ee-a73d-56c70f692df9', filename: 'road_sign.jpeg', byte_size: 44056, created_at: '2023-12-28 18:10:20', purpose: 'assistants', metadata: {}, path: PosixPath('road_sign.jpeg')>], output_files=[]),\n",
       " ToolStep(info={'tool_name': 'ChatWithEB', 'tool_args': '{\"word\":\"BEWARE\"}'}, result='{\"response\": \"<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it\\'s very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}', input_files=[], output_files=[]),\n",
       " ToolStep(info={'tool_name': 'AddWordTool', 'tool_args': '{\"word\":\"BEWARE\",\"des\":\"<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it\\'s very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}'}, result='{\"result\": \"<BEWARE>单词已添加成功, 当前单词本中有如下单词：BEWARE，释义如下<单词翻译>: 当心、小心\\\\n\\\\n<近义词>: Careful, Cautious, Wary, Alert\\\\n\\\\n<反义词>: Reckless, Careless, Negligent, Unmindful\\\\n\\\\n<例句>:\\\\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\\\\n2. You should always beware of scams when shopping online. (在网上购物时，你应该始终小心诈骗。)\\\\n3. Beware of the icy road, it\\'s very slippery. (小心结冰的路面，非常滑。)\\\\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时，要小心蛇和其他野生动物。)\\\\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)\"}', input_files=[], output_files=[])]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Step为该Run中Agent所执行的相关操作，含有tool_name（调用工具的名称），tool_args（工具的入参），input_files（输入的文件）， output_files（输出的文件）\n",
    "response.steps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tool以及Memory相关用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<name: ChatWithEB, description: ChatWithEB是一款根据用户的提供的单词，获取一个具体的单词描述、翻译以及例句的工具>,\n",
       " <name: AddWordTool, description: 添加单词以及它的详细解释到词库当中>,\n",
       " <name: highacc-ocr/v1.8/OCR, server_url: https://tool-highacc-ocr.aistudio-hub.baidu.com/, description: 用于提取并识别图片上的文字及位置信息>]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取当前所有工具\n",
    "agent_all.get_tools()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 查找某个工具\n",
    "eb_tool = agent_all.get_tool(\"ChatWithEB\")\n",
    "# 取消某个工具\n",
    "agent_all.unload_tool(eb_tool)\n",
    "# 加载某个工具\n",
    "agent_all.load_tool(eb_tool)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<HumanMessage role: 'user', content: '帮我把图片中的第一个英语单词进行解释之后添加到单词本中\\n<file>file-local-4ea15200-a569-11ee-a73d-56c70f692df9</file>', token_count: 1110>,\n",
       " <AIMessage role: 'assistant', content: '我已经将BEWARE这个单词添加到单词本中，它的意思是当心、小心，还有其他的释义和例句。如果您还有其他问题或需要添加更多单词，请随时告诉我。', token_count: 39>]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取Agent的对话历史\n",
    "agent_all.memory.get_messages()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 重置Agent的对话历史\n",
    "agent_all.reset_memory()\n",
    "agent_all.memory.get_messages()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ernie",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
